287B - Pipeline - CodeForces Solution


binary search math *1700

Please click on ads to support us..

Python Code:

n, k= list(map(int,str.split(input())))

max_pos=(((k-1)*k)//2)+1
if n==1:
  print(0)
elif n<=k:
  print(1)
elif n>max_pos:
  print(-1)
else:
  m=((1+(1-(4*(n-max_pos)*2))**0.5)/2)
  if m*(m-1)+n>max_pos:
    m-=1
  print(int(k-m))

C++ Code:

// Online C++ compiler to run C++ program online
#include <bits/stdc++.h>
using namespace std;

int main() {
    long long n,k;
    cin>>n>>k;
    long long low=0,high=k;
    long long maxpipes=(k*(k-1))/2+1;
    while(low<=high){
        long long mid=low+(high-low)/2;
        long long poss=(k*mid)-((mid*(mid+1))/2)+1;
        if(poss<n)low=mid+1;
        else high=mid-1;
    }
    
    if(low>k){
        cout<<-1;
    }else cout<<low;
    return 0;
}


Comments

Submit
0 Comments
More Questions

1547B - Alphabetical Strings
1550A - Find The Array
118B - Present from Lena
27A - Next Test
785. Is Graph Bipartite
90. Subsets II
1560A - Dislike of Threes
36. Valid Sudoku
557. Reverse Words in a String III
566. Reshape the Matrix
167. Two Sum II - Input array is sorted
387. First Unique Character in a String
383. Ransom Note
242. Valid Anagram
141. Linked List Cycle
21. Merge Two Sorted Lists
203. Remove Linked List Elements
733. Flood Fill
206. Reverse Linked List
83. Remove Duplicates from Sorted List
116. Populating Next Right Pointers in Each Node
145. Binary Tree Postorder Traversal
94. Binary Tree Inorder Traversal
101. Symmetric Tree
77. Combinations
46. Permutations
226. Invert Binary Tree
112. Path Sum
1556A - A Variety of Operations
136. Single Number